package com.android.exchangeapp

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.activity.result.contract.ActivityResultContract
import com.android.exchangeapp.modle.SupportCurrency

data class SelectRequest(val selectTag: Int, val itemKey: String)

data class SelectResult(val selectTag: Int, val item: SupportCurrency?)

/**
 * Created by Matt on 2023/11/2.
 **/
class SelectCurrencyContract : ActivityResultContract<SelectRequest, SelectResult>() {
    companion object {
        private const val KEY_SELECT_ITEM = "select_item"
        fun getSelectKey(intent: Intent): String {
            return intent.getStringExtra(KEY_SELECT_ITEM) ?: ""
        }

        fun createData(data: SupportCurrency): Intent {
            return Intent().putExtra(KEY_SELECT_ITEM, data)
        }
    }

    private var mSelectTag = -1

    override fun createIntent(context: Context, input: SelectRequest): Intent {
        mSelectTag = input.selectTag
        return Intent(context, SupportListActivity::class.java)
            .putExtra(KEY_SELECT_ITEM, input.itemKey)
    }

    override fun parseResult(resultCode: Int, intent: Intent?): SelectResult {
        try {
            if (resultCode != Activity.RESULT_OK || intent == null) {
                return SelectResult(mSelectTag, null)
            }
            val supportCurrency = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                intent.getParcelableExtra(KEY_SELECT_ITEM, SupportCurrency::class.java)
            } else {
                intent.getParcelableExtra(KEY_SELECT_ITEM)
            }
            return SelectResult(mSelectTag, supportCurrency)
        } finally {
            mSelectTag = -1
        }
    }
}